package com.strongbj.iot.devices.newlight.response;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 抽象带自动反馈的抽象类
 * 
 * @author yuzhantao
 *
 */
public abstract class AbstractMessageReturnHandle implements IMessageHandle<NewLightReaderMessage, Object> {
	protected final Logger logger = LogManager.getLogger(this.getClass());
	protected NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils
			.getBean("newLightOSMessageFactory");

	/**
	 * 对数据的处理
	 * 
	 * @param ctx
	 * @param t
	 * @return
	 */
	public abstract Object dataHandle(ChannelHandlerContext ctx, NewLightReaderMessage t);

	/**
	 * 处理类的名称，用于日志打印。
	 * 
	 * @return
	 */
	public abstract String getHandleName();

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		try {
			this.dataHandle(ctx, t);
			sendRebindTagReturnMessage(ctx, Short.valueOf(t.getType()).byteValue(), t.getAddress(), (byte) 1);
		} catch (Exception e) {
			logger.error("", e);
			sendRebindTagReturnMessage(ctx, Short.valueOf(t.getType()).byteValue(), t.getAddress(), (byte) 0);
		}
		return null;
	}

	/**
	 * 发送绑签反馈命令
	 * 
	 * @param ctx
	 * @param deviceCode
	 */
	private void sendRebindTagReturnMessage(ChannelHandlerContext ctx, byte messageType, byte[] deviceCode,
			byte isSuccess) {
		byte[] sendData = { isSuccess };
		byte[] req = newLightOSMessageFactory.createNewLightOSMessage(deviceCode, messageType, sendData,
				T.getTimeStamp());
		ByteBuf bs = Unpooled.copiedBuffer(req);
		Channel channel = ctx.channel();

		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("发送{}反馈命令成功 设备编号:{} 发送内容:{}", getHandleName(), deviceCode,
							ByteUtil.byteArrToHexString(req));
				} else {
					logger.debug("发送{}反馈命令失败 设备编号:{} 发送内容:{}", getHandleName(), deviceCode,
							ByteUtil.byteArrToHexString(req));
				}
			}

		});
	}
}
